<template>
  <div class="blog-editor">
    <!-- 顶部导航栏 -->
    <div class="editor-header">
      <div class="header-left">
        <i class="el-icon-arrow-left" @click="goBack"></i>
        <span class="draft-status">{{ autoSaveStatus }}</span>
      </div>
      <div class="header-actions">
        <el-button type="info" plain size="small" @click="previewArticle">
          <i class="el-icon-view"></i> {{ messages[currentLanguage].preview }}
        </el-button>
        <el-button type="primary" size="small" @click="saveArticle">
          <i class="el-icon-upload2"></i> {{ messages[currentLanguage].publish }}
        </el-button>
      </div>
    </div>

    <!-- 主编辑区域 -->
    <div class="editor-main">
      <!-- 左侧编辑区 -->
      <div class="editor-content">
        <!-- 标题输入 -->
        <div class="title-section">
          <el-input
            v-model="article.title"
            :placeholder="messages[currentLanguage].titlePlaceholder"
            class="title-input"
            maxlength="50"
            show-word-limit
          >
            <template #prefix>
              <i class="el-icon-edit"></i>
            </template>
          </el-input>
        </div>

        <!-- 封面图片上传 -->
        <div class="cover-section">
          <el-upload
            class="cover-uploader"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleCoverSuccess"
          >
            <img v-if="coverUrl" :src="coverUrl" class="cover-image">
            <i v-else class="el-icon-plus cover-uploader-icon"></i>
          </el-upload>
          <span class="upload-tip">{{ messages[currentLanguage].coverTip }}</span>
        </div>

        <!-- 富文本编辑器 -->
        <div class="editor-section">
          <quill-editor 
            ref="quillEditor"
            v-model="content"
            :options="editorOptions"
            @change="onEditorChange"
          />
        </div>
      </div>

      <!-- 右侧设置面板 -->
      <div class="editor-sidebar">
        <el-card class="setting-card">
          <template #header>
            <div class="card-header">
              <span>{{ messages[currentLanguage].articleSettings }}</span>
            </div>
          </template>
          
          <!-- 文章设置表单 -->
          <el-form label-position="top" size="small">
            <!-- 语言选择 -->
            <el-form-item :label="messages[currentLanguage].language">
              <el-select v-model="language" class="full-width">
                <el-option label="中文" value="zh"></el-option>
                <el-option label="English" value="en"></el-option>
              </el-select>
            </el-form-item>

            <!-- 可见性设置 -->
            <el-form-item :label="messages[currentLanguage].visibility">
              <el-select v-model="visibility" class="full-width">
                <el-option
                  v-for="option in visibilityOptions"
                  :key="option.visibilityid"
                  :label="option.name"
                  :value="option.visibilityid"
                >
                  <span style="float: left">{{ option.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">
                    <i :class="getVisibilityIcon(option.visibilityid)"></i>
                  </span>
                </el-option>
              </el-select>
            </el-form-item>

            <!-- 标签选择 -->
            <el-form-item :label="messages[currentLanguage].tags">
              <el-select
                v-model="selectedTags"
                multiple
                filterable
                class="full-width"
                :placeholder="messages[currentLanguage].tagsPlaceholder"
              >
                <el-option
                  v-for="tag in tagList"
                  :key="tag.tagId"
                  :label="tag.name"
                  :value="tag.tagId"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <!-- 原创声明 -->
            <el-form-item>
              <el-checkbox v-model="isOriginal">
                {{ messages[currentLanguage].originalArticle }}
              </el-checkbox>
              <el-tooltip :content="messages[currentLanguage].originalTip" placement="top">
                <i class="el-icon-question"></i>
              </el-tooltip>
            </el-form-item>

            <!-- 版权信息 -->
            <el-form-item :label="messages[currentLanguage].copyright">
              <el-input
                v-model="article.copyright"
                type="textarea"
                :rows="2"
                :placeholder="messages[currentLanguage].copyrightPlaceholder"
              ></el-input>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </div>

    <!-- 预览对话框 -->
    <el-dialog
      :title="messages[currentLanguage].preview"
      v-model="previewVisible"
      width="70%"
      class="preview-dialog"
    >
      <div class="preview-content">
        <h1>{{ article.title }}</h1>
        <div class="preview-meta">
          <span><i class="el-icon-time"></i> {{ formatDate(new Date()) }}</span>
          <span><i class="el-icon-user"></i> {{ authorName }}</span>
        </div>
        <div class="preview-body" v-html="content"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { messages } from "@/languages/addBlog.js";
import axios from 'axios';

export default {
  name: "BlogEditor",
  props: {
    currentLanguage: {
      type: String,
      default: "zh",
    },
  },
  components: {
    quillEditor: () => import('vue-quill-editor').then(m => m.quillEditor)
  },
  data() {
    return {
      article: {
        title: "",
        copyright: "",
        updatedAt: new Date().toISOString(),
      },
      content: "",
      visibility: "",
      selectedUsers: [],
      selectedTags: [],
      selectedRelatedArticles: [],
      visibilityOptions: [],
      userList: [],
      tagList: [],
      relatedArticleList: [],
      tagSearch: "",
      articleSearch: "",
      language: 'zh',
      isOriginal: false, // 是否为原创文章
      editorOptions: {
        placeholder: messages[this.currentLanguage].placeholder,
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote', 'code-block'],
            [{ 'header': 1 }, { 'header': 2 }],
            [{ 'list': 'ordered'}, { 'list': 'bullet' }],
            [{ 'indent': '-1'}, { 'indent': '+1' }],
            ['link', 'image'],
            ['clean']
          ],
          clipboard: {
            // 使用自定义的 Clipboard 模块
            matchVisual: false
          }
        }
      },
      messages: messages,
      // 校验信息
      titleError: "",
      contentError: "",
      visibilityError: "",
      coverUrl: "",
      previewVisible: false,
      autoSaveStatus: "已保存",
      authorName: localStorage.getItem('username') || '作者',
      autoSaveTimer: null,
    };
  },
  computed: {
    filteredTagList() {
      return this.tagList.filter(tag => {
        return tag.name.includes(this.tagSearch);
      });
    },
    filteredRelatedArticleList() {
      return this.relatedArticleList.filter(article => {
        return article.title.includes(this.articleSearch);
      });
    },
  },
  created() {
    this.fetchParameterSettings();
  },
  mounted() {
    // 使用 MutationObserver 监听编辑器内容变化
    if (this.$refs.quillEditor) {
      const editor = this.$refs.quillEditor.quill;
      const observer = new MutationObserver((mutations) => {
        mutations.forEach((mutation) => {
          if (mutation.type === 'childList') {
            this.onEditorChange({
              html: editor.root.innerHTML,
              text: editor.getText()
            });
          }
        });
      });

      observer.observe(editor.root, {
        childList: true,
        subtree: true
      });

      // 在组件销毁时断开观察器
      this.$once('hook:beforeDestroy', () => {
        observer.disconnect();
      });
    }
  },
  methods: {
    async fetchParameterSettings() {
      const account = localStorage.getItem('account'); // 获取当前登录的账户
      try {
        const response = await axios.get('/api/doc/base/request', {
          params: { account: account }
        });
        if (response.data.code === 200) {
          const { blogTags, blogLinks, visibilities } = response.data.data;
          this.tagList = blogTags;
          this.relatedArticleList = blogLinks;
          this.visibilityOptions = visibilities;
        } else {
          console.error('获取参数设置失败:', response.data.message);
        }
      } catch (error) {
        console.error('请求失败:', error);
      }
    },
    validateData() {
      this.titleError = "";
      this.contentError = "";
      this.visibilityError = "";
  
      // 标题校验
      if (!this.article.title) {
        this.titleError = "标题必填！";
      } else if (this.article.title.length > 20) {
        this.titleError = "标题不能超过20字！";
      }
  
      // 内容校验
      if (!this.content) {
        this.contentError = "内容必填！";
      } else if (this.content.length < 100) {
        this.contentError = "内容不能少于100字！";
      }
  
      // 可见范围校验
      if (!this.visibility) {
        this.visibilityError = "可见范围必选！";
      }
  
      // 返回校验结果
      return !this.titleError && !this.contentError && !this.visibilityError;
    },
    async saveArticle() {
      console.log("保存文章");
      if (this.validateData()) {
        const formattedData = {
          title: this.article.title,
          content: this.content,
          copyright: this.article.copyright,
          visibility: this.visibility,
          selectedTags: this.selectedTags,
          selectedRelatedArticles: this.selectedRelatedArticles,
          authorId: localStorage.getItem('account'),
          spaceId: this.$route.query.spaceId,
          isOriginal: this.isOriginal, // 新增字段
          language: this.language // 新增字段
        };
        
        console.log("Formatted Data:", formattedData);
        // 发送保存请求的代码可以在这里添加
        try {
          const response = await axios.post('/api/doc/saveBlogs', formattedData);
          if (response.data.code === 200) {
            // 文章保存成功后处理
            console.log('文章保存成功');
            // 可能添加跳转到文章列表页面的逻辑
          } else {
            console.error('保存失败:', response.data.message);
          }
        } catch (error) {
          console.error('请求失败:', error);
        }
      }
    },
    getVisibilityIcon(visibilityId) {
      const icons = {
        1: 'el-icon-view',
        2: 'el-icon-lock',
        3: 'el-icon-user'
      }
      return icons[visibilityId] || 'el-icon-view'
    },
    formatDate(date) {
      return new Date(date).toLocaleDateString()
    },
    // 返回上一页
    goBack() {
      this.$router.go(-1);
    },

    // 预览文章
    previewArticle() {
      this.previewVisible = true;
    },

    // 发布文章
    async publishArticle() {
      if (this.validateData()) {
        try {
          await this.saveArticle();
          this.$message.success(this.messages[this.currentLanguage].publishSuccess);
          this.$router.push('/blog-management');
        } catch (error) {
          this.$message.error(this.messages[this.currentLanguage].publishError);
        }
      }
    },

    // 处理封面上传成功
    handleCoverSuccess(res, file) {
      if (res.code === 200) {
        this.coverUrl = res.data.url;
        this.$message.success(this.messages[this.currentLanguage].uploadSuccess);
      } else {
        this.$message.error(this.messages[this.currentLanguage].uploadError);
      }
    },

    // 编辑器内容变化处理
    onEditorChange({ html, text }) {
      this.content = html;
      this.startAutoSave();
    },

    // 开始自动保存
    startAutoSave() {
      if (this.autoSaveTimer) {
        clearTimeout(this.autoSaveTimer);
      }
      
      this.autoSaveStatus = "正在保存...";
      this.autoSaveTimer = setTimeout(async () => {
        try {
          await this.saveArticle();
          this.autoSaveStatus = "已保存";
        } catch (error) {
          this.autoSaveStatus = "保存失败";
          console.error('自动保存失败:', error);
        }
      }, 2000);
    },

    // 组件销毁时清理
    beforeDestroy() {
      if (this.autoSaveTimer) {
        clearTimeout(this.autoSaveTimer);
      }
    },
  },

  // 监听属性变化
  watch: {
    'article.title'() {
      this.startAutoSave();
    },
    visibility() {
      this.startAutoSave();
    },
    selectedTags() {
      this.startAutoSave();
    }
  },
};
</script>

<style scoped>
.blog-editor {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 24px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.editor-main {
  display: flex;
  flex: 1;
  padding: 24px;
  gap: 24px;
  overflow: hidden;
}

.editor-content {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  padding: 24px;
  overflow-y: auto;
}

.editor-sidebar {
  width: 320px;
}

.title-input {
  font-size: 24px;
  margin-bottom: 20px;
}

.cover-uploader {
  width: 100%;
  height: 200px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  margin-bottom: 20px;
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.setting-card {
  position: sticky;
  top: 24px;
}

.full-width {
  width: 100%;
}

.preview-dialog .preview-content {
  padding: 20px;
}

.preview-meta {
  color: #909399;
  margin: 16px 0;
}

.preview-meta span {
  margin-right: 20px;
}

/* 添加响应式设计 */
@media (max-width: 1200px) {
  .editor-main {
    flex-direction: column;
  }
  
  .editor-sidebar {
    width: 100%;
  }
}

/* 修复嵌套样式的语法错误 */
.preview-meta {
  color: #909399;
  margin: 16px 0;
}

.preview-meta span {
  margin-right: 20px;
}

/* 添加一些新的样式 */
.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 100%;
  line-height: 200px;
  text-align: center;
}

.upload-tip {
  font-size: 12px;
  color: #606266;
  margin-top: 8px;
}

.draft-status {
  font-size: 14px;
  color: #909399;
  margin-left: 16px;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-left i {
  font-size: 20px;
  cursor: pointer;
}

.header-left i:hover {
  color: #409EFF;
}
</style>
  